package com.ly.jwt.utils;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.ly.jwt.db.entity.UserAccount;
import org.apache.commons.lang3.StringUtils;

import javax.servlet.http.HttpServletRequest;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * token生成
 *
 * @Author: 宇
 * @catalogue: com.example.hotelmanagement.utils
 * @Date: 1999/9/9 9:99
 * @Version: 1.0
 */
public class TokenUtil {
    /*
        过期时间为24小时，毫秒计时的---毫秒--》秒--》分--》小时--》天
        private static final long EXPIRE_TIME= 60 * 24 * 60 * 1000;
     */
    private static final long EXPIRE_TIME = 60 * 1000 * 60 * 24;

    /**
     * 密钥，注意这里如果真实用到，应当设置到复杂点，相当于私钥的存在。如果被人拿到，相当于它可以自己制造token了。
     */
    private static final String TOKEN_SECRET = "token-ly";  //密钥盐

    /**
     * 签名生成
     *
     * @param userAccount
     * @return
     */
    public static String sign(UserAccount userAccount) {
        String token = null;
        try {
            Date expiresAt = new Date(System.currentTimeMillis() + EXPIRE_TIME);
            token = JWT.create()
                    //存入token中，accId账号id，username用户名，role权限
                    .withClaim("id", userAccount.getId())
                    .withClaim("username", userAccount.getUsername())
                    .withClaim("role", userAccount.getRole())
                    .withExpiresAt(expiresAt)
                    // 使用了HMAC256加密算法。
                    .sign(Algorithm.HMAC256(TOKEN_SECRET));
        } catch (Exception e) {
            e.printStackTrace();
        }
        return token;
    }

    /**
     * 签名验证
     *
     * @param token
     * @return
     */
    public static boolean verify(String token) {
        if (StringUtils.isBlank(token)) {
            throw new BaseException("4001","token为空");
        }
        try {
            JWTVerifier verifier = JWT.require(Algorithm.HMAC256(TOKEN_SECRET)).build();//自定义的
            DecodedJWT jwt = verifier.verify(token);
            System.out.println("认证通过：");
            System.out.println("id: " + jwt.getClaim("id").asLong());
            System.out.println("username: " + jwt.getClaim("username").asString());
            System.out.println("role: " + jwt.getClaim("role").asString());
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            System.out.println("过期时间：" + sdf.format(jwt.getExpiresAt()));
            return true;
        } catch (Exception e) {
            return false;
        }
    }

    /**
     * <p> 获得id,操作人 </p>
     *
     * @param request
     * @return int
     * @Description getIdByToken
     * @date 1999/9/9 9:99
     */
    public static Long getIdByToken(HttpServletRequest request) {
        String token = request.getHeader("token");
        DecodedJWT jwt = JWT.decode(token);
        return jwt.getClaim("id").asLong();
    }

    /**
     * <p> 获得用户名 </p>
     *
     * @param request
     * @return java.lang.String
     * @Description getUserNameByToken
     * @date 1999/9/9 9:99
     */
    public static String getUserNameByToken(HttpServletRequest request) {
        String token = request.getHeader("token");
        DecodedJWT jwt = JWT.decode(token);
        return jwt.getClaim("username").asString();
    }

    /**
     * <p> 获得权限 </p>
     *
     * @param request
     * @return java.lang.String
     * @Description getRoleByToken
     * @date 1999/9/9 9:99
     */
    public static String getRoleByToken(HttpServletRequest request) {
        String token = request.getHeader("token");
        DecodedJWT jwt = JWT.decode(token);
        return jwt.getClaim("role").asString();
    }
}

